package BalanceAction;

use strict;

use Athena::WebAPI::Response;
use Athena::BalanceView;
use Athena::Engine::Balance;

sub execute {
  my $stInvocant = shift(@_);
  my $rRequest = shift(@_);
  my $rConn = shift(@_);  
  my %hParams = ( @_ );
  my $stParams = \%hParams;
  my $rResponse = undef;
  my $stActionName = 'BalanceAction';
  $rRequest->action($stActionName);
  my $stAction = $rRequest->param($stActionName);
  my $stErrMsg = "";
  my $stLb = $rRequest->cookie('AthenaEngineUrl') 
    || $rRequest->cookie('AthenaEngineHost') 
      . ":" . $rRequest->cookie('AthenaEnginePort');

  my $rFarms = Athena::Engine::Farm->new($rConn);
  $rFarms->refresh();
  my $rBalancedFarms = Athena::Engine::Balance->new($rConn);
  my $key;
  foreach $key (keys(%{$rFarms->{table}})) {
    $rBalancedFarms->farmAdd($rFarms->{table}->{$key}->{name});
  }
  $rBalancedFarms->refresh();

  my $rHiddenFields = {
		       $rRequest->getActionParam() => $rRequest->action(),
		       $stActionName => '',
		      };
  my $rView = BalanceView->new('lb' => $stLb,
			       'err_msg' => $stErrMsg,
			       'hidden_fields' => $rHiddenFields,
			       'action_name' => $stActionName,
			       'body_style' => $stParams->{body_style},
			       'table_style' => $stParams->{table_style},
			       'farms_bal' => $rBalancedFarms->{farms}
			       );

  $rResponse = Response->new($rView);
  return $rResponse;
}

1;
